<template>
  <div class="fbDrawer">
    <beetles-drawer title="新增账户" :visible.sync="visible" :before-close="handleClose" :auto-size="true"
                    :close-on-press-escape="false"
                    :wrapperClosable="false"
                    :modal-append-to-body="false">
      <el-table :data="monitorData" style="width: 100%" class="monitor-table"
                :header-cell-style="{color:'#101010'}" size="small">
        <el-table-column type="index" align="center" width="40px" label="#" fixed></el-table-column>
        <el-table-column prop="name" label="账户名称" width="150px">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="platformId" label="账户ID" width="180px">
          <template slot-scope="scope">
            {{ scope.row.platformId }}
          </template>
        </el-table-column>
        <el-table-column prop="offerId" label="订单名称" width="150px">
          <template slot-scope="scope">
            <el-select :ref="'offerSelect'+scope.$index" v-if="scope.row.offerSelectVisible" size="mini"
                       filterable
                       v-model="scope.row.offerId"
                       placeholder="请选择订单名称" @change="handleBlurSelect(scope.$index,'offerId')" @blur="handleBlurSelect(scope.$index,'offerId')">
              <el-option v-for="(item,index) in offerList" :key="index" :value="item.id" :label="item.name"
              >
              </el-option>
            </el-select>
            <el-button v-else :type="scope.row.offerId?'primary':'warning'" size="mini" plain
                       @click="showEditItem(scope.$index,'offerId')">
              {{ scope.row.offerId !== undefined ? formatOfferName(scope.row.offerId) : '请选择订单名称' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="platform" label="媒体" width="130px">
          <template slot-scope="scope">
            {{ scope.row.platform }}
          </template>
        </el-table-column>
        <el-table-column prop="bindStatus" label="绑定状态" width="110px">
          <template slot-scope="scope">
            <el-select :ref="'bindStatusSelect'+scope.$index" v-if="scope.row.bindStatusSelectVisible" size="mini"
                       filterable
                       v-model="scope.row.bindStatus"
                       placeholder="请选择订单名称" @change="handleBlurSelect(scope.$index,'bindStatus')" @blur="handleBlurSelect(scope.$index,'bindStatus')">
              <el-option v-for="(item,index) in bindStatusList" :key="index" :value="item.value"
                         :label="item.label"
              >
              </el-option>
            </el-select>
            <el-button v-else type="primary" size="mini" plain @click="showEditItem(scope.$index,'bindStatus')">
              {{ formatBindStatus(scope.row.bindStatus) }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="owner" label="账户所有人" width="150px">
          <template slot-scope="scope">
            <el-select :ref="'ownerSelect'+scope.$index" v-if="scope.row.ownerSelectVisible" size="mini"
                       filterable
                       v-model="scope.row.owner"
                       placeholder="请选择订单名称" @change="handleBlurSelect(scope.$index,'owner')" @blur="handleBlurSelect(scope.$index,'owner')">
              <el-option v-for="(item,index) in userList" :key="index" :value="item.id" :label="item.realName"
              ></el-option>
            </el-select>
            <el-button v-else :type="scope.row.owner?'primary':'warning'" size="mini" plain
                       @click="showEditItem(scope.$index,'owner')">
              {{ scope.row.owner ? formatUserName(scope.row.owner) : '请选择所有人' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="账户运营人" width="150px">
          <template slot-scope="scope">
            <el-select :ref="'operatorSelect'+scope.$index" v-if="scope.row.operatorSelectVisible" size="mini"
                       filterable
                       v-model="scope.row.operator"
                       placeholder="请选择订单名称"@change="handleBlurSelect(scope.$index,'operator')" @blur="handleBlurSelect(scope.$index,'operator')">
              <el-option v-for="(item,index) in userList" :key="index" :value="item.id" :label="item.realName"
              ></el-option>
            </el-select>
            <el-button v-else :type="scope.row.operator?'primary':'warning'" size="mini" plain
                       @click="showEditItem(scope.$index,'operator')">
              {{ scope.row.operator ? formatUserName(scope.row.operator) : '请选择运营人' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="110px">
          <template slot-scope="scope">
            <el-select :ref="'statusSelect'+scope.$index" v-if="scope.row.statusSelectVisible" size="mini"
                       filterable
                       v-model="scope.row.status"
                       placeholder="请选择订单名称" @change="handleBlurSelect(scope.$index,'status')" @blur="handleBlurSelect(scope.$index,'status')">
              <el-option v-for="(item,index) in statusList" :key="index" :value="item.value"
                         :label="item.label"
              >
              </el-option>
            </el-select>
            <el-button v-else type="primary" size="mini" plain @click="showEditItem(scope.$index,'status')">{{
                formatStatus(scope.row.status)
              }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" width="50px" label="操作" fixed="right">
          <template slot-scope="scope">
            <div style="text-align: center;font-size: 25px" @click="delRow(scope.$index)" class="delBtn">
              <i class="el-icon-circle-close"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div style="display: flex;justify-content: center;align-items: center">
          <el-button size="medium" type="primary" plain @click="submit"
                     :disabled="loading">保存
          </el-button>
          <el-button size="medium" @click="handleClose">
            取消
          </el-button>
        </div>
      </template>
    </beetles-drawer>
  </div>
</template>

<script>
import {batchAddAccounts} from "@/api/business/account"
import BeetlesDrawer from "@/components/beetles/beetles-drawer";

export default {
  name: "accountAddFb",
  components: {BeetlesDrawer},
  model: {
    prop: 'visible',
    event: 'close'
  },
  props: {
    visible: {
      type: Boolean
    },
    account: {
      type: Object
    },
    advAddPlatform: {
      type: Array
    },
    userList: {
      type: Array
    },
    offerList: {
      type: Array
    },
  },
  data() {
    return {
      loading: false,
      disabledPlatform: false,
      bindStatusList: [
        {label: '已绑定', value: 0},
        {label: '解绑', value: 1},
        {label: '被禁止', value: 2}
      ],
      statusList: [
        {label: '活跃', value: 0},
        {label: '暂停', value: 1}
      ],
      saving: false,
      dialogVisible: false,
      // 当前账户
      monitorData: [],
    }
  },
  created() {
    this.formatMonitorData()
  },
  computed: {
    getSize() {
      return window.innerWidth > 1300 ? '1250' : '80%';
    },
  },
  watch: {
    monitorData() {
      // 如果删除完账户自动关闭弹窗
      if (this.monitorData.length === 0) {
        this.$emit('close', false)
      }
    }
  },
  methods: {
    // 初始化数据
    formatMonitorData() {
      let data = this.account;
      let list = []
      if (data.accounts && data.accounts.length > 0) {
        data.accounts.forEach(item => {
          list.push({
            name: item.name,
            platformId: item.platformId,
            platform: data.platform,
            bindStatus: 0,
            status: 0,
            offerSelectVisible: false,
            bindStatusSelectVisible: false,
            ownerSelectVisible: false,
            operatorSelectVisible: false,
            statusSelectVisible: false,
          })
        })
      } else {
        list.push({});
      }
      this.monitorData = list
    },
    delRow(i) {
      if (this.monitorData.length - 1 > i) {
        for (const key in this.monitorData[i]) {
          if (this.monitorData[i][key] !== 'up' && this.monitorData[i + 1][key] === 'up') {
            this.monitorData[i + 1][key] = this.monitorData[i][key]
          }
        }
      }
      this.monitorData.splice(i, 1)
    },
    submit() {
      // 校验是否晚上数据
      let vail = true
      this.monitorData.forEach(item => {
        if (!item.offerId || !item.owner || !item.operator) {
          vail = false
        }
      })
      if (!vail) return this.$message.warning('订单名称，账户所有人和账户运营人为必选！请完善内容再提交')
      this.loading = true;
      batchAddAccounts(this.monitorData).then(res => {
        if (res.data.code === 200) {
          this.monitorData = [];
          this.$message.success('新增成功!')
          this.$emit('submit')
          this.loading = false;
        } else {
          this.loading = false;
        }
      }).catch(() => {
        this.loading = false;
      })
    },
    handleClose() {
      this.loading = false;
      this.monitorData = [];
      this.$emit('close', false)
    },
    getOwner: function () {
      this.userList.find((v) => {
        if (v.realName === 'ads4each') {
          return v.id;
        }
      })
      return null;
    },
    formatBindStatus(value) {
      return this.bindStatusList.find(item => item.value === value).label
    },
    formatStatus(value) {
      return this.statusList.find(item => item.value === value).label
    },
    formatOfferName(value) {
      return this.offerList.find(item => item.id === value).name
    },
    formatUserName(value) {
      return this.userList.find(item => item.id === value).realName
    },
    // 展示选择修改框
    showEditItem(index, type) {
      switch (type) {
        case 'offerId':
          this.monitorData[index].offerSelectVisible = true
          this.$nextTick(() => {
            this.$refs['offerSelect' + index].toggleMenu()
            // TODO 无法获得select框的焦点
            this.$refs['offerSelect' + index].focus()
          })
          break;
        case 'bindStatus':
          this.monitorData[index].bindStatusSelectVisible = true
          this.$nextTick(() => {
            this.$refs['bindStatusSelect' + index].toggleMenu()
            this.$refs['bindStatusSelect' + index].focus()
          })
          break;
        case 'owner':
          this.monitorData[index].ownerSelectVisible = true
          this.$nextTick(() => {
            this.$refs['ownerSelect' + index].toggleMenu()
            this.$refs['ownerSelect' + index].focus()
          })
          break;
        case 'operator':
          this.monitorData[index].operatorSelectVisible = true
          this.$nextTick(() => {
            this.$refs['operatorSelect' + index].toggleMenu()
            this.$refs['operatorSelect' + index].focus()
          })
          break;
        case 'status':
          this.monitorData[index].statusSelectVisible = true
          this.$nextTick(() => {
            this.$refs['statusSelect' + index].toggleMenu()
            this.$refs['operatorSelect' + index].focus()
          })
          break;
      }
      // this.dialogVisible = true
      // console.log(this.monitorData[index]);
      // this.currentType = type
      // this.curruentAccount = this.monitorData[index]
    },
    // 选择器失去焦点事件
    handleBlurSelect(index, type) {
      console.log('blur')
      setTimeout(() => {
        switch (type) {
          case 'offerId':
            this.monitorData[index].offerSelectVisible = false
            break;
          case 'bindStatus':
            this.monitorData[index].bindStatusSelectVisible = false
            break;
          case 'owner':
            this.monitorData[index].ownerSelectVisible = false
            break;
          case 'operator':
            this.monitorData[index].operatorSelectVisible = false
            break;
          case 'status':
            this.monitorData[index].statusSelectVisible = false
            break;
        }
      }, 500)
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .el-drawer.rtl {
  //overflow: hidden;
}

/deep/ .el-drawer {
  outline: none;

  &__body {
    height: 100%;
    overflow: hidden;
  }
}

.monitor-table {
  ///deep/ .el-form-item {
  //  margin-bottom: 0;
  //}
}

.delBtn {
  &:hover {
    color: #78aff9;
  }
}

.addBtn {
  width: 100px;
  margin-top: 2em;
  margin-left: 2em;
  display: flex;
  color: #34A9FF;
  cursor: pointer;

  &:hover {
    color: #78aff9;
  }
}
</style>
